﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.IO;

namespace MainAPI.Controllers
{

    public enum UserFunctionResult
    {
        已存在用户 = 0, 注册成功 = 1, 注册失败 = -1, 登录成功 = 2, 密码不合法 = -2, 用户名不合法 = -3, 登录失败 = -4, 用户不存在 = -5, 密码错误 = -6
    }
    [ApiController]
    [Route("[action]")]
    public class UserController : ControllerBase
    {

        int InsertUser(string id, string pw)
        {
            var mySql = Setting.GetSQLConnect();
            mySql.Open();
            MySqlCommand command = mySql.CreateCommand();
            command.CommandText = string.Format($@"INSERT INTO `{Setting.UserTable}` (`user_id`, `user_passwd`) VALUES ('{id}', '{pw}')");
            int r = command.ExecuteNonQuery();
            mySql.Close();
            return r;
        }
        int UpdateUser(string id, string pw)
        {
            var mySql = Setting.GetSQLConnect();
            mySql.Open();
            MySqlCommand command = mySql.CreateCommand();
            command.CommandText = string.Format($@"UPDATE `Users` SET `user_passwd` = '{pw}' WHERE `Users`.`user_id` = '{id}';");
            int r = command.ExecuteNonQuery();
            mySql.Close();
            return r;
        }

        private readonly ILogger<User> _logger;

        public UserController(ILogger<User> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public Order GetOrder(string id)
        {
            Order order;
            using (FileStream fs = new FileStream(Setting.订单路径.FullName + "\\" + id + ".order", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                StreamReader reader = new StreamReader(fs);
                string s = reader.ReadToEnd();
                order = System.Text.Json.JsonSerializer.Deserialize<Order>(s);
                var c = Setting.GetSQLConnect();
                c.Open();
                var cmd = c.CreateCommand();
                cmd.CommandText = $@"SELECT * FROM {Setting.OrderTable} WHERE order_id = '{id}'";
                var data = cmd.ExecuteReader();
                List<OrderBaseInfo> result = new List<OrderBaseInfo>();
                while (data.Read())
                {
                    int isok = data.GetInt32("isFinsh");
                    order.IsDone = isok == 1 ? true : false;
                }
                c.Close();
                reader.Close();
            }
            return order;
        }
        [HttpGet]
        public List<OrderBaseInfo> GetOrderList(string userid)
        {
            var c = Setting.GetSQLConnect();
            c.Open();
            var cmd = c.CreateCommand();
            cmd.CommandText = $@"SELECT * FROM {Setting.OrderTable} WHERE user_id = '{userid}'";
            var data = cmd.ExecuteReader();
            List<OrderBaseInfo> result = new List<OrderBaseInfo>();
            while (data.Read())
            {
                string oid = data.GetString("order_id");
                int isok = data.GetInt32("isFinsh");
                result.Add(new OrderBaseInfo() { OrderID = oid, isFinsh = isok, UserID = userid });
            }
            c.Close();
            return result;
        }

        [HttpPost]
        public int CreateOrder(string userid, string phone, string address, [FromBody] List<OrderGood> items)
        {
            try
            {
                Order order = new Order(userid);
                order.Address = address;
                order.Phone = phone;
                order.Items.AddRange(items);
                var mySql = Setting.GetSQLConnect();
                mySql.Open();
                MySqlCommand command = mySql.CreateCommand();
                string d = order.IsDone ? "1" : "0";
                command.CommandText = string.Format($@"INSERT INTO `{Setting.OrderTable}` (`user_id`, `order_id`,`isFinsh`) VALUES ('{userid}', '{order.OrderID}','{d}')");
                int r = command.ExecuteNonQuery();
                mySql.Close();


                string infopath = order.OrderID + ".order";
                using (FileStream fs = new FileStream(Setting.订单路径.FullName + "\\" + infopath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    StreamWriter writer = new StreamWriter(fs);
                    writer.Write(System.Text.Json.JsonSerializer.Serialize(order));
                    writer.Close();
                }
                return 1;
            }
            catch
            {
                return 0;
            }

        }

        [HttpGet]
        public Good GetGood(int id)
        {
            var c = Setting.GetSQLConnect();
            c.Open();
            MySqlCommand command = c.CreateCommand();
            command.CommandText = $@"SELECT * FROM {Setting.GoodTable} WHERE goods_id = '{id}'";
            var r = command.ExecuteReader();
            while (r.Read())
            {
                string n = r.GetString("goods_name");
                double p = r.GetDouble("goods_price");
                c.Close();
                return new Good(n, id.ToString(), p);
            }
            c.Close();
            return null;
        }
        [HttpGet]
        public int GoodsCount()
        {
            var c = Setting.GetSQLConnect();
            c.Open();
            MySqlCommand command = c.CreateCommand();
            command.CommandText = $@"SELECT COUNT(*) FROM {Setting.GoodTable}";
            var r = command.ExecuteReader();
            while (r.Read())
            {
                int re = r.GetInt32(0);
                c.Close();
                return re;
            }
            c.Close();
            return -1;
        }


        [HttpGet]
        public string ParseCode(int code)
        {
            return Enum.ToObject(typeof(UserFunctionResult), code).ToString();
        }

        [HttpGet]
        public bool UserChangePasswordBySpecialCode(string name, string code, string newpassword)
        {
            if (newpassword.Length < 8)
                return false;
            if (SpecialCodeVerify(name, code))
            {
                try
                {
                    UpdateUser(name, newpassword);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            return false;
        }
        [HttpGet]
        public bool UserChangePasswordByOldPassword(string name, string old, string newpassword)
        {
            if (newpassword.Length < 8)
                return false;
            if (Login(name, old) == UserFunctionResult.登录成功)
            {
                try
                {
                    UpdateUser(name, newpassword);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            return false;
        }

        [HttpGet]
        public string UserSpecialCode(string name, string password)
        {
            if (Login(name, password) == UserFunctionResult.登录成功)
            {
                return new User(name, password).SpecialCode;
            }
            else
                return "用户名与密码不和";
        }
        bool SpecialCodeVerify(string name, string code)
        {
            code = code.ToUpper();
            if (Setting.ExistUser(name))
            {
                return Setting.MakeCodeGenerator(name).Verify(code, Setting.GetUserPassword(name));
            }
            else
                return false;
        }

        [HttpGet]
        public UserFunctionResult Login(string name, string password)
        {
            if (name.Length < 6 || name.Length > 18)
                return UserFunctionResult.用户名不合法;
            else if (password.Length < 8 || password.Length > 24)
                return UserFunctionResult.密码不合法;
            else
            {
                if (Setting.ExistUser(name))
                {
                    try
                    {
                        if (Setting.CheckUserPassword(name, password))
                            return UserFunctionResult.登录成功;
                        else
                            return UserFunctionResult.密码错误;
                    }
                    catch
                    {
                        return UserFunctionResult.登录失败;
                    }
                }
                else
                    return UserFunctionResult.用户不存在;

            }
        }

        //[HttpPost]
        //public string UploadData(List<User> users)
        //{
        //    return users.Count.ToString();
        //}
        [HttpGet]
        public FileContentResult GetImage(string id)
        {

            string path = Setting.图片路径.Name + "\\" + id + ".jpg";
            string type = "image/jpeg";
            return new FileContentResult(System.IO.File.ReadAllBytes(path), type);
        }

        [HttpGet]
        public UserFunctionResult Rigister(string name, string password)
        {
            if (name.Length < 6 || name.Length > 18)
                return UserFunctionResult.用户名不合法;
            else if (password.Length < 8 || password.Length > 24)
                return UserFunctionResult.密码不合法;
            else
            {
                if (Setting.ExistUser(name))
                    return UserFunctionResult.已存在用户;
                else
                {
                    try
                    {
                        InsertUser(name, password);
                        return UserFunctionResult.注册成功;
                    }
                    catch
                    {
                        return UserFunctionResult.注册失败;
                    }


                }

            }


        }
    }
}
